﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting.Internal;

using SManaApi.Services;

using SManaModel;
using SManaModel.entities;
using SManaModel.utils;

using System.Net;

namespace SManaApi.Controllers
{
    /// <summary>
    /// 上传模块
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class UploadController : MasterController<UploadController>
    {
        private readonly Microsoft.AspNetCore.Hosting.IWebHostEnvironment _hostingEnvironment;
        private readonly FileService _fileService;
        public UploadController(ILogger<UploadController> logger, MyDbContext context, IWebHostEnvironment hostingEnvironment, FileService fileService) : base(logger, context)
        {
            _hostingEnvironment = hostingEnvironment;
            _fileService = fileService;
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="formFiles"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult Post(IFormFileCollection formFiles)
        {
            MD5CodeUtil md5 = new();
            List<FileEntity> files = new();
            foreach (var file in formFiles)
            {
                var fileName = file.FileName;
                var extension = Path.GetExtension(fileName);
                Console.WriteLine(fileName);

                if (!Directory.Exists("UploadFile"))
                {
                    Directory.CreateDirectory("UploadFile");
                }

                var filePath = $"wwwroot/UploadFile/{fileName}";
                var fileFullPath = _hostingEnvironment.ContentRootPath + filePath;
                using (FileStream fs = System.IO.File.Create(fileFullPath))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }

                FileEntity fileEntity = new()
                {
                    Name = fileName,
                    Url = filePath,
                    Size = file.Length,
                    Type = extension,
                    Md5 = md5.GetMD5HashFromFile(fileFullPath)
                };
                files.Add(fileEntity);

            }

            var n  =_fileService.AddRange(files);
            Console.WriteLine("已写入: " + n + " 条数据");

            return ApiResult.Ok();
        }

    }
}
